package com.example.mygame.controller;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.mygame.R;
import com.example.mygame.pojo.User;
import com.example.mygame.service.SPSave;
import com.example.mygame.service.SqliteUtils;

import java.util.List;
import java.util.Map;

public class ModifyPassword extends AppCompatActivity {

    private EditText oldPassword;

    private EditText newPassword;

    private EditText newPasswordIsTrue;

    private Button modify;

    private SqliteUtils sqliteUtils;

    User finalUser = new User();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_password);

        oldPassword = findViewById(R.id.oldPassword);
        newPassword = findViewById(R.id.newPassword);
        newPasswordIsTrue = findViewById(R.id.newPasswordisTrue);
        modify = findViewById(R.id.modify);

        sqliteUtils = new SqliteUtils(this);

        Intent getDataIntent = getIntent();

        String getUserName = getDataIntent.getStringExtra("userName");



        modify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<User> userList = sqliteUtils.queryFromDbByName(getUserName);
                for (User user : userList) {

                    finalUser = user;

                }

                if (oldPassword.getText().toString().equals(finalUser.getPassword())) {
                    if (newPassword.getText().toString().equals(newPasswordIsTrue.getText().toString())) {
                        finalUser.setPassword(newPassword.getText().toString());
                        sqliteUtils.updateData(finalUser);

                        Map<String, String> userInfo = SPSave.getUserInfo(ModifyPassword.this);

                        System.out.println(finalUser.getName());

                        if (userInfo.get("account").equals(finalUser.getName())) {
                            SPSave.saveUserInfo(ModifyPassword.this,finalUser.getName(),finalUser.getPassword());
                        }

                        Toast.makeText(getApplicationContext(), "修改成功",
                                Toast.LENGTH_SHORT).show();
                    }
                }
                Intent intent = new Intent(ModifyPassword.this, Login.class);

                startActivity(intent);
            }
        });


    }
}